<?php

// 关闭错误信息
error_reporting(0);

require '../base.php';

define('VERSION', '1.0.0');


// 引入错误捕捉

include __DIR__ . DIRECTORY_SEPARATOR . 'error_handler.php';

/**
 * @title 自定义md5
 * @param type $value
 * @return type
 */
function my_md5($value, $salt = APP_SALT) {
    $password = md5(md5($value) . $salt);
    return $password;
}

switch ($_POST['a']) {
    // 环境检查
    case 'env_check' : {
            $json = array();
            // php 版本
            $php_version = explode('-', phpversion());
            $php_version = $php_version[0];
            $json['version'] = $php_version;
            $json['version_ok'] = strnatcasecmp($php_version, '7.0.0') >= 0 ? true : false;
            // 扩展检测
            $json['ext_curl'] = extension_loaded('curl');
            $json['ext_pdo_mysql'] = extension_loaded('pdo_mysql');
            $json['ext_gd'] = extension_loaded('gd');
            // 目录检测
            $json['dir_uploads'] = is_dir(APP_DIR . '/uploads') && is_writable(APP_DIR . '/uploads');
            $json['dir_install'] = is_dir(APP_DIR . '/install') && is_writable(APP_DIR . '/install');
            //$json['dir_extra'] = is_dir('../../application/extra') && is_writable('../../application/extra');
            //$json['dir_runtime'] = is_dir('../../runtime') && is_writable('../../runtime');

            echoMsg(0, $json);
        }
        break;
    // 数据库连接检查
    case 'db_valid' : {
            try {
                new PDO(sprintf("mysql:host=%s;dbname=", $_POST['f-dbaddress']), $_POST['f-dbusername'], $_POST['f-dbpassword']);
                echoMsg(0);
            } catch (Exception $e) {
                echoMsg(-1, '数据库连接失败！请检查扩展 pdo_mysql 是否已经开启或者数据库账号密码是否正确');
            }
        }
        break;
    // 数据库安装
    // @TODO 当数据库存在时，提示覆盖？
    case 'db_install': {
            $pdo = getDb($_POST['f-dbaddress'], $dbconfig['dbname'], $_POST['f-dbusername'], $_POST['f-dbpassword']);
            if ($pdo instanceof PDO) {
                try {
                    $pdo->exec("drop database if exists " . $_POST['f-dbname'] . ";");
                    $db_found = $pdo->exec("CREATE DATABASE IF NOT EXISTS " . $_POST['f-dbname'] . " DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_general_ci;") !== false;



                    if ($db_found) {

                        $db11 = array();
                        $db11['host'] = $_POST['f-dbaddress'];
                        $db11['dbname'] = $_POST['f-dbname'];
                        $db11['user'] = $_POST['f-dbusername'];
                        $db11['pwd'] = $_POST['f-dbpassword'];

                        // 导入sqls目录下的所有sql文件
                        $sqlarr = glob(APP_DIR . "/install/sqls/*.sql");


                        foreach ($sqlarr as $value) {
                            run_sql_file($value, $db11, $pdo);
                        }


                        $account = $_POST['f-account'];
                        $pass = $_POST['f-pass'];

                        if (empty($account) || empty($pass)) {
                            echoMsg(-1, "管理员账号或密码不能为空");
                        } else {
                            // 超级管理员
                            $pdo->exec("INSERT INTO `tb_system_user` (`id`, `username`, `password`, `nickname`, `status`) VALUES (1, '" . $account . "', '" . my_md5($pass, $_POST['f-salt']) . "','超级管理员', 1);");
                            $pdo->exec('commit;');

                            // 返回成功
                            echoMsg(0);
                        }
                    } else {
                        echoMsg(-1, "数据库创建失败");
                    }
                } catch (Exception $ex) {
                    echoMsg(-1, $ex->getMessage());
                }
            } else {
                echoMsg(-1, '数据库连接失败！请检查扩展 pdo_mysql 是否已经开启或者数据库账号密码是否正确');
            }
        }
        break;
    case 'config_install': {

            $configDb = file_get_contents(dirname(__FILE__) . '/../../application/database.php');
            $configDb = preg_replace('/\'hostname\'(.*?)=> \'(.*?)\',/', '\'hostname\'${1}=> \'' . $_POST['f-dbaddress'] . '\',', $configDb);
            $configDb = preg_replace('/\'database\'(.*?)=> \'(.*?)\',/', '\'database\'${1}=> \'' . $_POST['f-dbname'] . '\',', $configDb);
            $configDb = preg_replace('/\'username\'(.*?)=> \'(.*?)\',/', '\'username\'${1}=> \'' . $_POST['f-dbusername'] . '\',', $configDb);
            $configDb = preg_replace('/\'password\'(.*?)=> \'(.*?)\',/', '\'password\'${1}=> \'' . $_POST['f-dbpassword'] . '\',', $configDb);
            $configDb = preg_replace('/\'prefix\'(.*?)=> \'(.*?)\',/', '\'prefix\'${1}=> \'tb_\',', $configDb);
            file_put_contents('../../application/database.php', $configDb);

            $configBase = file_get_contents(dirname(__FILE__) . '/../../application/extra/base.php');
            $configBase = preg_replace('/\'title\'(.*?)=> \'(.*?)\',/', '\'title\'${1}=> \'' . $_POST['f-title'] . '\',', $configBase);
            $configBase = preg_replace('/\'domain\'(.*?)=> \'(.*?)\',/', '\'domain\'${1}=> \'' . $_POST['f-domain'] . '\',', $configBase);
            file_put_contents('../../application/extra/base.php', $configBase);

            $base = file_get_contents(dirname(__FILE__) . '/../base.php');
            $base = preg_replace("/'APP_SALT', '(.*?)'/", "'APP_SALT', '".$_POST['f-salt']."'", $base);
            file_put_contents(dirname(__FILE__) . '/../base.php', $base);

            // 锁定安装
            touch(dirname(__FILE__) . '/install.lock');

            if (file_exists(dirname(__FILE__) . '/install.lock')) {
                echoMsg(0);
            } else {
                echoMsg(-1, "请检查/install/目录权限是否可写");
            }
        }
}

/**
 * @param $sql_file
 * @param $dbconfig
 * @param $pdo PDO
 */
function run_sql_file($sql_file, $dbconfig, $pdo) {

    define('DB_CHARSET', 'utf8');
    $dbname = $dbconfig['dbname'];

    /* ############ 数据文件分段执行 ######### */
    $sql_str = file_get_contents($sql_file);
    $piece = array(); // 数据段
    preg_match_all("@([\s\S]+?;)\h*[\n\r]@is", $sql_str, $piece); // 数据以分号;\n\r换行  为分段标记
    !empty($piece[1]) && $piece = $piece[1];
    $count = count($piece);
    if ($count <= 0) {
        exit('mysql数据文件: ' . $sql_file . ' , 不是正确的数据文件. 请检查安装包.');
    }

    $tb_list = array(); // 表名列表
    preg_match_all('@CREATE\h+TABLE\h+[`]?([^`]+)[`]?@', $sql_str, $tb_list);
    !empty($tb_list[1]) && $tb_list = $tb_list[1];

    $pdo->exec("USE $dbname");

    // 开始循环执行
    for ($i = 0; $i < $count; $i++) {
        if (!is_array($piece[$i])) {
            $pdo->exec($piece[$i]);
        }
    }
    $pdo->exec('commit;');
}

/**
 * @param $host
 * @param $db
 * @param $user
 * @param $pass
 */
function getDb($host, $db, $user, $pass) {
    try {
        $pdo = new PDO(sprintf("mysql:host=%s;dbname=%s", $host, $db), $user, $pass);
        $pdo->exec("SET NAMES utf8mb4;");
        return $pdo;
    } catch (Exception $ex) {
        return false;
        // '数据库连接失败！请检查扩展PDO是否打开或者配置文件中账号密码是否正确！
    }
}
